package com.gpj.sqlbuilder.template;

import com.gpj.sqlbuilder.utils.TextUtils;
import lombok.Getter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
  * @className Template
  * @description 
  *   模板对象基类,用于定义模板对象公共信息
  * @author GPJ
  * @date 2021/4/16 21:05
  * @version 1.0
  **/
@Getter
public abstract class Template {
	protected String id;

	protected int start;
	protected int tail;

	protected Map<String, Object> variables = new HashMap<>();

	protected StringBuffer template;
	protected StringBuffer sql = new StringBuffer();

	private Template parent;

	protected List<Template> children = new ArrayList<>();

	public Template(int start, int tail, Template parent) {
		this.start = start;
		this.tail = tail;
		this.parent = parent;

		if(parent != null){
			this.id = parent.getId() + "-" + (parent.getChildren().size() + 1);
			this.template = new StringBuffer(TextUtils.substr(start, tail, parent.getTemplate()));
		}
	}

	abstract protected void build();

	public String toString(){
		int len = 50;
		if(template.length() < len + 3){
			return this.getClass().getSimpleName() + ":[" + id + "]:\t" + template;
		}else{
			return this.getClass().getSimpleName() + ":[" + id + "]:\t" +
					template.substring(0, len) + "..." + template.substring(template.length() - len);
		}
	}
}
